package com.friend.chat.page.widget

import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes


/**
 * @des popupWindow帮助类
 * @author sam
 * @date 2023/1/19
 */
class PopupWindowHelper {
    private var mTouchView: View
    private var popupWindow: PopupWindow? = null

    constructor(touchView: View, @LayoutRes layoutId: Int) {
        this.mTouchView = touchView
        initView(layoutId)
    }

    private fun initView(layoutId: Int) {
        val v: View =
            LayoutInflater.from(mTouchView.context).inflate(layoutId, null, false)
        popupWindow = PopupWindow(
            v,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true
        )
        popupWindow!!.isTouchable = true
        popupWindow!!.setBackgroundDrawable(ColorDrawable(0x00000000))
        popupWindow?.setTouchInterceptor(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                return false
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        })
    }
    fun setClickListener(@IdRes id: Int, callback: () -> Unit): PopupWindowHelper {
        popupWindow?.contentView?.findViewById<View>(id)?.setOnClickListener {
            callback()
            popupWindow?.dismiss()
        }
        return this
    }

    fun show(xOff: Int, yOff: Int): PopupWindowHelper {
        popupWindow?.showAsDropDown(mTouchView, xOff, yOff)
        return this
    }

    fun dismiss(){
        popupWindow?.dismiss()
    }


}